const path = require('path');

const classes = {
    'info': 'weui_icon_info weui_icon_msg',
    'warn': 'weui_icon_info weui_icon_msg',
    'error': 'weui_icon_warn weui_icon_msg',
    'success': 'weui_icon_success weui_icon_msg',
}

const titles = {
    'success': '成功',
    'info': '提示',
    'warn': '请注意',
    'error': '抱歉，出错了'
}

const statuses = {
    'success': 200,
    'info': 200,
    'warn': 200,
    'error': 500
}

module.exports = function(config, app) {
    let spa;
    if (config.devServer) {
        const serve = require('@wanhu/koa-serve-spa/dev-proxy');
        spa = serve(config.devServer, {
            baseUrl: '/',
            locals: {
                BAIDU_TONGJI_CODE: app.config.baiduTongjiCode,
                INSURANCE_PACKAGE_ID: app.config.insurance.sellPackageId,
                WEIXIN_MINI_APP_ID: app.config.weixin.miniAppId,
                ADS_IS_SHOW: app.config.ads.isShow,
                PARTNER_BAIJI_URL: app.config.baiji.url,
            },
            contextualLocals: ctx => ({
                _csrf: ctx.csrf,
                ...ctx.spaData
            })
        });
    } else if (config.path) {
        const serve = require('@wanhu/koa-serve-spa');
        spa = serve(config.path, {
            baseUrl: '/',
            locals: {
                BAIDU_TONGJI_CODE: app.config.baiduTongjiCode,
                INSURANCE_PACKAGE_ID: app.config.insurance.sellPackageId,
                WEIXIN_MINI_APP_ID: app.config.weixin.miniAppId,
                ADS_IS_SHOW: app.config.ads.isShow,
                PARTNER_BAIJI_URL: app.config.baiji.url,
            },
            contextualLocals: ctx => ({
                _csrf: ctx.csrf,
                ...ctx.spaData
            })
        });
    }

    return async (ctx, next) => {
        ctx.staticAssets = spa;
        ctx.indexPage = async function(title, state) {
            ctx.spaData = {
                title,
                INITIAL_STATE: state
            };
            await spa(ctx, next);
            return ctx.body;
        }
        ctx.throwMessage = (msg, levelOrOpts) => {
            const e = new Error(msg);
            if (!levelOrOpts) {
                e.viewLevel = 'error';
            } else if (typeof levelOrOpts === 'string') {
                e.viewLevel = levelOrOpts || 'error';
            } else if (typeof levelOrOpts === 'object') {
                e.viewLevel = levelOrOpts.level || 'error';
                e.status = levelOrOpts.status;
                e.title = levelOrOpts.title;
            }
            throw e;
        }
        try {
            await next();
        } catch (e) {
            let viewClass, viewMessage, defaultTitle, defaultStatus;
            if (e.viewLevel) {
                viewClass = classes[e.viewLevel] || classes.error;
                viewMessage = e.message;
                defaultTitle = titles[e.viewLevel] || titles.error;
                defaultStatus = statuses[e.viewLevel] || statuses.error;
            } else {
                viewClass = classes.error;
                viewMessage = '未知错误，请稍后重试或联系客服';
                defaultTitle = titles.error;
                defaultStatus = statuses.error;
                ctx.logger.error(e);
            }
            ctx.status = e.status || defaultStatus;
            ctx.body = `<html><head><title>${e.title || defaultTitle}</title>
                <meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
                <link rel="icon" href="">
                <link rel="stylesheet" type="text/css" href="../../assets/css/weui.css"></head>
                <body><div class="weui_msg"><div class="weui_icon_area">
                <i class="${viewClass}"></i></div><div class="weui_text_area">
                <h4 class="weui_msg_title">${viewMessage}</h4></div></div>
                </body></html>`;
        }


    }
}
